package main

import (
	"fmt"
	"gitee.com/frank2020/joy4/av"
	"gitee.com/frank2020/joy4/codec/h264parser"

	//"gitee.com/frank2020/joy4/codec/h264parser"
	"gitee.com/frank2020/joy4/format"
	"gitee.com/frank2020/joy4/format/rtmp"
)

func init() {
	format.RegisterAll()
}

func main() {
	server := &rtmp.Server{}

	server.HandlePublish = func(conn *rtmp.Conn) {
		streams, _ := conn.Streams()

		var h264Codec h264parser.CodecData
		// 流信息
		for _, stream := range streams {
			if stream.Type().IsAudio() {
				astream := stream.(av.AudioCodecData)
				fmt.Println(astream.Type(), astream.SampleRate(), astream.SampleFormat(), astream.ChannelLayout())
			} else if stream.Type().IsVideo() {
				vstream := stream.(av.VideoCodecData)
				fmt.Println(vstream.Type(), vstream.Width(), vstream.Height())
				codec := vstream.(h264parser.CodecData)
				fmt.Println("sps : %s", codec.SPS())
				fmt.Println("pps : %s", codec.PPS())

				h264Codec = codec

			}
		}

		codec, err := h264parser.NewCodecDataFromSPSAndPPS(h264Codec.SPS(), h264Codec.PPS())
		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Printf("codec: %+v\n", codec)

		// 关联输入和输出
		//avutil.CopyPackets(ch.que, conn)
		for i := 0; i < 50; i++ {
			var pkt av.Packet
			var err error
			if pkt, err = conn.ReadPacket(); err != nil {
				break
			}

			if streams[pkt.Idx].Type().IsVideo() {
				fmt.Println(streams[pkt.Idx].Type(), "len", len(pkt.Data), "keyframe", pkt.IsKeyFrame)

				nalus, _ := h264parser.SplitNALUs(pkt.Data)
				for _, v := range nalus {
					fmt.Printf("index:%d  type:%d\n", i, v[0]&0x1f)
				}

			}
		}
	}

	server.ListenAndServe()

	// ffmpeg -re -i movie.flv -c copy -f flv rtmp://localhost/movie
	// ffmpeg -f avfoundation -i "0:0" .... -f flv rtmp://localhost/screen
	// ffplay http://localhost:8089/movie
	// ffplay http://localhost:8089/screen
}
